<?php

namespace app\admin\controller\ykjp\sell;

use app\common\controller\Backend;
use think\Db;

/**
 * 销售订单主管理
 *
 * @icon fa fa-circle-o
 */
class Selllist extends Backend {

    /**
     * Selllist模型对象
     * @var \app\admin\model\ykjp\sell\Selllist
     */
    protected $model = null;
    protected $distinguish = true;

    public function _initialize() {
        parent::_initialize();
        $this->model = new \app\admin\model\ykjp\sell\Selllist;
    }

    /**
     * 查看详情
     */
    public function detail($ids) {
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $detail = $this->model
                ->where($where)
                ->where('firmid', $this->auth->firmid)
                ->order($sort, $order)
                ->where("id", $ids)
                ->select();
        $productModel = new \app\admin\model\ykjp\sell\Product;
        $product = $productModel->with(['products'])->where("sell_id", $ids)->select();
        $arr;
        if ($product) {
            foreach ($product as $key => $value) {
                $a = json_decode($value['products']['prop']);
                $value['products']['prop'] = $this->model->object_array($a);
                $arr[] = $value;
            }
        }
        $this->assign("detail", $detail);
        $this->assign("product", $product);
        return $this->view->fetch("detail");
    }

    /**
     * 编辑销售单
     */
    public function edit($ids = null) {

        if ($this->request->isAjax()) {

            if ($ids == null) {
                $this->error(__('fail'));
            }
            $product = $this->request->param("product/a");
            $row = $this->request->param("row/a");
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $isRset = $this->model
                    ->where("firmid", $this->auth->firmid)
                    ->where("id", $ids)
                    ->select();
            //获取客户模型
            $customerModel = new \app\admin\model\ykjp\information\basisinfo\Customerinfo;
            $customer = $customerModel->get(['id' => $row['customer_info_id'], "firmid" => $this->auth->firmid]);
            if (!$isRset) {
                $this->error(__('fail'));
            }
            if (isset($isRset[0]['status_list']) && $isRset[0]['status_list'] != 1) {
                $this->error(__('not editable'));
            }
            $row['code'] = (isset($row['code']) && $row['code'] != "") ? $row['code'] : "YK" . date("ymdHis", time()) . rand(1000, 9999);
            $row['customer_name'] = $customer["name"];  //客户姓名
            $row['delivery_time'] = strtotime($row['delivery_time']);  //交货日期
            $row['billing_time'] = strtotime($row['billing_time']);  //制单日期
            $row['updatetime'] = time();  //更新时间
            $dataRow = $this->model
                    ->where("id", $ids)
                    ->update($row);

            if (!$product) {
                $this->error(__('Product cannot be empty'));
            }
            $product = json_decode($product[0]);
            $product = $this->model->object_array($product);

            //销售副表
            $sellProduct = new \app\admin\model\ykjp\sell\Product;
            $where = [];
            foreach ($product as $key => $val) {
                $id = $val['data_id'];
                unset($val["data_id"]);
                $val['updatetime'] = time();
                if ($id) {
                    $up = $sellProduct->where("id", $id)->where('firmid', $this->auth->firmid)->update($val);
                    $where[] = $id;
                } else {
                    $val['sell_id'] = $ids;
                    $val['createtime'] = time();
                    $val['firmid'] = $this->auth->firmid;
                    $inser = $sellProduct->insertGetId($val);
                    if ($inser) {
                        $where[] = $inser;
                    }
                }
            }
            $deletTime['deletetime'] = time();
            $update = $sellProduct->where("sell_id", $ids)->where("id", "not in", $where)->update($deletTime);
            if ($update) {
                $this->success(null, null, ['result' => "success"]);
            }
            $this->success(null, null, ['result' => "success"]);
        }
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();

        $detail = $this->model
                ->where($where)
                ->where('firmid', $this->auth->firmid)
                ->order($sort, $order)
                ->where("id", $ids)
                ->where("status_list", 1)
                ->select();
        if (!$detail) {
            $this->error(__('not editable'));
        }
        $productModel = new \app\admin\model\ykjp\sell\Product;
        $product = $productModel->with(['products'])->where("sell_id", $ids)->select();
        if ($product) {
            foreach ($product as $key => $value) {
                $a = json_decode($value['products']['prop']);
                $value['products']['prop'] = $this->model->object_array($a);
            }
        }
        $this->assign("detail", $detail);
        $this->assign("product", $product);
        return $this->view->fetch();
    }

    /**
     * 作废销售单
     */
    public function abandon() {

        $ids = $this->request->post('ids');  //要作废的销售单ID
        $reason = $this->request->post('reason');  //作废理由
        //判断当前销售单是否存在未作废的出库单
        $res = Db::name('ykjp_delivery')
                ->where('sell_id', $ids)
                ->where('firmid', $this->auth->firmid)
                ->where('status_list > 0')
                ->count();
        if ($res > 0) {
            $this->error(null, null, ['result' => "提交失败，请先作废对应的出库单！"]);
        }

        //执行作废修改
        $abandon_res = Db::name('ykjp_sell')
                ->where('id', $ids)
                ->where('firmid', $this->auth->firmid)
                ->where('status_list > 0')
                ->update([
            'reason' => $reason,
            'status_list' => '-1'
        ]);
        if ($abandon_res) {
            $this->success(null, null, ['result' => "作废成功！"]);
        } else {
            $this->error(null, null, ['result' => "提交作废失败！"]);
        }
    }

    /**
     * 反审核
     */
    public function Anti($ids = null) {
        if ($ids) {
            $data = $this->model->where("firmid", $this->auth->firmid)->where("status_list", "in", [2, 3, 4, 5])->where("id", $ids)->find();
            if ($data) {
                $purchaseProduct = new \app\admin\model\ykjp\purchase\Product;
                $result = 0;
                //只有未生成出库单的销售单才可以反审核
                $isCount = Db::name('ykjp_delivery')->where("firmid", $this->auth->firmid)->where("sell_id", $ids)->count();
                if ($isCount == 0) {  //如果出库单数量为空，则可以进行反审核
                    $updateData = array("updatetime" => time(), "status_list" => "1", "reason" => null, 'cause' => null);
                    $up = $this->model->where("id", $ids)->update($updateData);
                    if ($up) {
                        $this->success(null, null, array("result" => "success"));
                    } else {
                        $this->error(__("operate fail"));
                    }
                } else {
                    $this->error(__('您已生成出库单，无法进行反审核'));
                }
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 确认订单完成
     */
    public function goodsok($ids = null) {


        list($where, $sort, $order, $offset, $limit) = $this->buildparams();

        if ($ids) {  //通过
            $data = array("status_list" => 10, "purman_id" => $this->auth->id, "updatetime" => time());
            $update = $this->model
                    ->where('firmid', $this->auth->firmid)
                    ->where("id", "in", $ids)
                    ->update($data);
            if ($update) {
                $this->success(null, null, array("result" => "success"));
            }
            $this->error("operation fail");
        }

        $this->error("Illegal operation");
    }

    /**
     * 删除
     */
    // public function del($ids = "")
    // {
    //     if ($ids) {
    //         $pk = $this->model->getPk();
    //         $adminIds = $this->getDataLimitAdminIds();
    //         if (is_array($adminIds)) {
    //             $this->model->where($this->dataLimitField, 'in', $adminIds);
    //         }
    //         if($this->distinguish&&$this->auth->firmid!=0){
    //             $list = $this->model->where($pk, 'in', $ids)->where("firmid",$this->auth->firmid)->select(); 
    //         }else{
    //             $list = $this->model->where($pk, 'in', $ids)->select();
    //         }
    //         $count = 0;
    //         $count2 = 0;
    //         Db::startTrans();
    //         try {
    //             foreach ($list as $k => $v) {
    //                 $sell_id = $v->id;  //获取销售单id
    //                 $productModel = new \app\admin\model\ykjp\sell\Product;  //初始化销售单副表模型
    //                 $product_list = $productModel->where('sell_id',$sell_id)->select();  //获取关联对象
    //                 foreach ($product_list as $key => $value) {
    //                     $count2 += $value->delete();
    //                 }
    //                 $count += $v->delete();
    //             }
    //             Db::commit();
    //         } catch (PDOException $e) {
    //             Db::rollback();
    //             $this->error($e->getMessage());
    //         } catch (Exception $e) {
    //             Db::rollback();
    //             $this->error($e->getMessage());
    //         }
    //         if ($count && $count2) {
    //             $this->success();
    //         } else {
    //             $this->error(__('No rows were deleted'));
    //         }
    //     }
    //     $this->error(__('Parameter %s can not be empty', 'ids'));
    // }
}
